<script setup lang="ts" name="userInfo">

import {Delete, EditPen} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox, ElTable} from "element-plus";
import {onMounted, reactive, ref} from "vue";
import {deleteData, getAllUsers, post, put} from "@/net";
import type {UserType} from "@/type/User"
import type {GetType} from "@/type/GetType";
import {UserRules} from "@/utils/rules/userRule"

// 功能函数
const fetchUserListAndRefresh = () => {
  getAllUserData();
}

const closeUpdataDialog = () => {
  dialogUpdateVisible.value = false;
};
const closeAddDialog = () => {
  dialogAddVisible.value = false;
}

const handleOperationResult = (success: boolean) => {
  if (success) {
    fetchUserListAndRefresh();
  }
};

// todo 添加用户
const dialogAddVisible = ref(false);
const addUserForm = reactive({
  uid: 0,
  name: '',
  email: '',
  telephoneNumber: '',
  CN_ID: '',
  address: '',
  permission: '用户',
  gender: '其他',
  remark: '',
  username: '',
  password: '',
})


const submitAddUser = () => {

  post('api/user/add', addUserForm, () => {
    ElMessage.success("添加成功");
    fetchUserListAndRefresh();
    handleOperationResult(true);
  }, () => {
    ElMessage.warning("添加失败")
    fetchUserListAndRefresh();
    closeAddDialog();
  }, () => {
    ElMessage.error("发生了错误");
    fetchUserListAndRefresh();
    closeAddDialog();
  })
}


//删除用户

const handleDeleteUser = (index: number, row: UserType) => {
  ElMessageBox.confirm("你要删除这个用户吗?", "提示", {
    icon: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    deleteData("api/user/delete", {email: row.email}, () => {
      ElMessage.success("删除成功");
      handleOperationResult(true);
    }, () => {
      ElMessage.warning("删除失败,")
    }, () => {
      ElMessage.error("删除error")
    });
  }).catch((err) => {
    ElMessage.error(err)
  })
}


//修改用户
const dialogUpdateVisible = ref(false);
let Userdata: UserType[] = reactive([]);

let updateUserForm = reactive<UserType>({
  uid: 0,
  name: '',
  email: '',
  telephoneNumber: '',
  CN_ID: '',
  address: '',
  permission: '',
  gender: '',
  remark: '',
  username: '',
  password: '',
});


const handleUpdateUser = (row: Partial<typeof updateUserForm>) => {
  // updateUser=Object.assign({},updateUser,row);
  Object.keys(row).forEach(key => {
    if (updateUserForm.hasOwnProperty(key)) {
      (updateUserForm as any)[key] = row[key]; // 或者使用更安全的类型断言或类型守卫
    }
  });

  dialogUpdateVisible.value = true;
}


const submitUpdate = async () => {
  const index = Userdata.findIndex(item => item.uid === updateUserForm.uid);
  try {
    let user = {
      uid: updateUserForm.uid,
      email: updateUserForm.email,
      name: updateUserForm.name,
      telephoneNumber: updateUserForm.telephoneNumber,
      CN_ID: updateUserForm.CN_ID,
      permission: updateUserForm.permission,
      gender: updateUserForm.gender,
      remark: updateUserForm.remark,
      username: updateUserForm.username,
      password: updateUserForm.password
    }
    await put("api/user/update", user, () => {
      Userdata[index] = updateUserForm;
      ElMessage.success("修改成功");
      handleOperationResult(true);
    })
  } catch (err) {
    console.log(err)
  }
}

// 获取用户

const getAllUserData = async () => {
  try {
    const response: GetType = await getAllUsers('api/user/getAll');
    Userdata.splice(0, Userdata.length, ...response.message);
    Userdata.forEach(item => {
      item.password = null;
    })
  } catch (err) {
    console.log(err)
  }
}

// 常量

const genderOptions = [
  {
    label: '男',
    value: '男'
  },
  {
    label: '女',
    value: '女'
  },
  {
    label: '其他',
    value: '其他'
  }
]
const permissionOptions = [
  {
    label: '管理员',
    value: '管理员'
  },
  {
    label: '用户',
    value: '用户'
  }
]

// Vue生命周期函数

onMounted(() => {
  getAllUserData();
})

</script>
<template>
  <div style="display: flex; flex-flow: row nowrap; justify-content: space-between; margin-bottom: 10px">
    <div>
      <span>信息管理 > 用户信息</span>
    </div>
    <div style="margin-right: 60px">
      <el-button type="primary" @click="dialogAddVisible = true">添加用户</el-button>
    </div>
  </div>

  <el-table ref="table" :data="Userdata" style="width: 100%"
            height="70vh" border
  ><!--            @selection-change="handleSelectionChange"-->
    <el-table-column type="index" label="序号"/>
    <el-table-column prop="username" label="用户名"/>
    <el-table-column prop="name" label="姓名"/>
    <el-table-column prop="gender" label="性别"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column prop="telephoneNumber" label="电话号码"/>
    <el-table-column prop="CN_ID" label="身份证"/>
    <el-table-column prop="address" label="住房"/>
    <el-table-column prop="permission" label="身份"/>
    <el-table-column prop="remark" label="备注"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button name="update" @click="handleUpdateUser(scope.row)" type="warning" :icon="EditPen" circle/>
        <el-button name="delete" plain @click="handleDeleteUser(scope.$index,scope.row)" type="danger" :icon="Delete"
                   circle/>
      </template>

    </el-table-column>
  </el-table>

  <el-dialog
      title="添加用户信息"
      :model-value="dialogAddVisible"
      width="50%"
      @close="closeAddDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             :rules="UserRules"
             style="width: 500px;"
    >
      <div style="display:flex;">
        <div>
          <el-form-item label="姓名" :required="true" style="width: 200px">
            <el-input v-model="addUserForm.name" prop="name" ></el-input>
          </el-form-item>
          <el-form-item label="性别" :required="true">
            <el-select v-model="addUserForm.gender"
                       placeholder="请选择"
                       style="width: 240px"
                       prop="gender" >
              <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="电话号码" style="width: 300px">
            <el-input v-model="addUserForm.telephoneNumber" prop="telephoneNumber" ></el-input>
          </el-form-item>
          <el-form-item label="身份证" style="width: 300px;">
            <el-input v-model="addUserForm.CN_ID" prop="CN_ID"></el-input>
          </el-form-item>
        </div>
        <div style="margin-left: 100px">
          <el-form-item label="用户名" :required="true" style="width: 300px">
            <el-input v-model="addUserForm.username" prop="username" ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :required="true" >
            <el-input v-model="addUserForm.email" prop="email" ></el-input>
          </el-form-item>
          <el-form-item label="身份" :required="true" style="width: 300px">
            <el-select v-model="addUserForm.permission" prop="permission" placeholder="请选择" style="width: 300px" >
              <el-option
                  v-for="item in permissionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" :required="true">
            <el-input type="password" v-model="addUserForm.password" prop="password" show-password ></el-input>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="地址" style="width: 700px;">
        <el-input v-model="addUserForm.address" prop="adderss" placeholder="详细地址(xx栋-xxx号)" rules="addressRules">
          <template #prepend>xxx小区</template>
        </el-input>
      </el-form-item>
      <el-form-item label="备注" style="width: 700px;">
        <el-input type="textarea" v-model="addUserForm.remark"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitAddUser">确定</el-button>
        <el-button @click="closeAddDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  添加用户  -->
  <el-dialog
      title="修改用户信息"
      :model-value="dialogUpdateVisible"
      width="50%"
      @close="closeUpdataDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             :rules="UserRules"
             style="width: 500px;"
    >
      <div style="display:flex;">
        <div>
          <el-form-item label="姓名" :required="true" style="width: 200px">
            <el-input v-model="updateUserForm.name" prop="name" id="real_name_update"></el-input>
          </el-form-item>
          <el-form-item label="性别" :required="true" >
            <el-select v-model="updateUserForm.gender" id="gender_update"
                       placeholder="请选择"
                       style="width: 240px"
                       prop="gender" >
              <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="电话号码" style="width: 300px">
            <el-input v-model="updateUserForm.telephoneNumber" prop="telephoneNumber" id="phone_update"></el-input>
          </el-form-item>
          <el-form-item label="身份证" style="width: 300px;">
            <el-input v-model="updateUserForm.CN_ID" prop="CN_ID"></el-input>
          </el-form-item>
        </div>
        <div style="margin-left: 100px">
          <el-form-item label="用户名" :required="true" style="width: 300px">
            <el-input v-model="updateUserForm.username" prop="username" id="username_update"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :required="true">
            <el-input v-model="updateUserForm.email" prop="email" id="email_update"></el-input>
          </el-form-item>
          <el-form-item label="身份" :required="true" style="width: 300px">
            <el-select v-model="updateUserForm.permission" prop="permission" placeholder="请选择" style="width: 300px" id="permission_update">
              <el-option
                  v-for="item in permissionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" :required="true">
            <el-input type="password" v-model="updateUserForm.password" prop="password" show-password id="password_update"></el-input>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="地址" style="width: 700px;">
        <el-input v-model="updateUserForm.address" prop="adderss" placeholder="详细地址(xx栋-xxx号)"
                  rules="addressRules">
          <template #prepend>xxx小区</template>
        </el-input>
      </el-form-item>
      <el-form-item label="备注" style="width: 700px;">
        <el-input type="textarea" v-model="updateUserForm.remark"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitUpdate" id="right_update_button">确定</el-button>
        <el-button @click="closeUpdataDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>


<style scoped>

</style>